package allocator;

import java.util.concurrent.Semaphore;
import java.util.logging.Logger;
/**
 *	Simple memory allocator using {@link Semaphore} to manage the number of free pages
 *
 */
public class MemoryAllocator implements IMemoryAllocator {
	
	private static final Logger LOGGER = Logger.getLogger("MEMORY_ALLOCATOR");

	private final Semaphore semaphore;
	
	public MemoryAllocator(int freePages) {
		this.semaphore = new Semaphore(freePages);
	}
	
	@Override
	public int request(int amount) throws InterruptedException {
		semaphore.acquire(amount);
		LOGGER.info("Allocator allocated free pages: " + amount);
		return amount;
	}

	@Override
	public void release(int amount) {
		semaphore.release(amount);
		LOGGER.info("Allocator released number of free pages: " + amount);
	}

	@Override
	public int getTotalAmount() {
		return semaphore.availablePermits();
	}

}
